import React, {Component} from 'react';
import './index.css'
import {Button, Modal} from "antd";
import storageUtil from '../../utils/storageUtil'
import LoginIcon from "../../pages/login/logo.svg";
import moment from "moment";
import {withRouter} from "react-router-dom";
import menuList from "../../config/menuConfig";
import memoryUtil from "../../utils/memoryUtil";

// 顶部导航
class Header extends Component {
    state = {
        currentTime: moment().format('YYYY-MM-DD HH:ss')//当前时间
    }

    //获取当前时间
    getTime =()=>{
        // setInterval是一个实现定时调用的函数
        this.intervalId=setInterval(()=>{
            const currentTime= moment().format('YYYY-MM-DD HH:ss')
            this.setState({currentTime})
        },1000)
    }

    //获取目录名
    getTitle = ()=>{
        let title
        const path = this.props.location.pathname
        menuList.forEach(item=>{
            if(item.key===path){
                title = item.title
            } else if(item.children){
                // const cItem = item.children.find(cItem => cItem.key===path)
                const cItem = item.children.find(cItem => path.indexOf(cItem.key)==0)
                if(cItem){
                    title=cItem.title
                }
            }
        })
        return title
    }

    logOut =()=>{
        Modal.confirm({
            content:'确认退出么？',
            onOk:()=>{
                console.log('OK')
                //删除local数据，跳转到登录页
                storageUtil.removeUser()
                memoryUtil.user={}
                this.props.history.replace('/login')
            },
            onCancel(){
                console.log('cancal')
            }
        })
    }
    /*
    第一次render()之后执行
     */
    componentDidMount() {
        this.getTime()
    }
    //卸载之前
    componentWillUnmount() {
        //清楚定时器
        clearInterval(this.intervalId)
    }

    render() {
        const {currentTime} = this.state
        const title=this.getTitle()
        const user=storageUtil.getUser()
        return (
            <div className="headerNav">
                <div style={{textAlign:'end',borderBottom:'1px solid #1677ff',height:40,paddingRight:10}}>
                    <span>欢迎,{user.username}</span>
                    <Button type="link" onClick={this.logOut}>退出</Button>
                </div>
                <div className="header-bottom">
                    <div className="header-bottom-left">{title}</div>
                    <div className="header-bottom-bottom">
                        <div>{currentTime}</div>
                        <img src={LoginIcon} alt="logo" style={{width:30,height:30}}/>
                        <div>晴</div>
                    </div>
                </div>
            </div>
        );
    }
}

export default withRouter(Header);